<?php

namespace Rabbitmq\Tool\RabbitMQTool;

use PhpAmqpLib\Exchange\AMQPExchangeType;
use PhpAmqpLib\Message\AMQPMessage;

class PublishBaseService
{
    /**
     * @var RabbitMQInstance
     */
    private $instance;

    /**
     * 队列负载
     * @var
     */
    protected $payload;

    /**
     * 队列
     * @var
     */
    protected $queue;

    /**
     * 交换机
     * @var
     */
    protected $exchange = '';

    /**
     * 交换机类型
     * @var
     */
    protected $exchangeType = AMQPExchangeType::DIRECT;

    protected $exchangePassive = false;

    protected $passive = false;

    /**
     * 路由键
     * @var
     */
    protected $routeKey = '';

    /**
     * 队列属性
     * @var
     */
    protected $properties = ['content_type' => 'text/plain','delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT];

    /**
     * 持久化设置
     * @var bool
     */
    private $durable = true;

    public function __construct()
    {
        $this->instance = new RabbitMQInstance();
    }
    /**
     * 队列设置
     * @param $queue
     * @return $this
     */
    public function setQueue($queue): PublishBaseService
    {
        $this->queue = $queue;
        return $this;
    }
    /**
     * 交换机设置
     * @param $exchange
     * @return $this
     */
    public function setExchange($exchange): PublishBaseService
    {
        $this->exchange = $exchange;
        return $this;
    }
    /**
     * 负载设置
     * @param $routeKey
     * @return $this
     */
    public function setRouteKey($routeKey): PublishBaseService
    {
        $this->routeKey = $routeKey;
        return $this;
    }

    /**
     * 负载设置
     * @param $payload
     * @return $this
     */
    public function setPayload($payload): PublishBaseService
    {
        $this->payload = json_encode($payload);
        return $this;
    }

    /**
     * 队列属性设置
     * @param $properties
     * @return $this
     */
    public function setProperties($properties): PublishBaseService
    {
        foreach ($properties as $property => $value) {
            $this->$property = $value;
        }
        return $this;
    }

    /**
     * @throws \Exception
     */
    public function handle()
    {
        $this->instance
            ->setExchange($this->exchange)
            ->setExchangeType($this->exchangeType)
            ->setPayload($this->payload)
            ->setProperties($this->properties)
            ->setQueue($this->queue)
            ->setDurable($this->durable)
            ->setQueuePassive($this->passive)
            ->setExchangePassive($this->exchangePassive)
            ->publish();
    }
}
